<script setup lang="ts">
import { computed, reactive, ref, watch, watchEffect } from 'vue'
const userInfo = reactive({
  familyName: 'zhangsan',
  lastName: 'lisi',
})

//computed 读取某个元素 当元素发生更改的时候可以拿取最新的值进行其他操作例如双向绑定
const userName = computed(() => userInfo.familyName + userInfo.lastName)
const userName2 = computed({
  get() {
    return userInfo.familyName + userInfo.lastName
  },
  set(val) {
    const nameArr = val.split(' ')
    userInfo.familyName = nameArr[0]
    userInfo.lastName = nameArr[1]
  },
})

//watch监听普通1个值
const num = ref(0)
watch(num, (newVal, oldVal) => {
  console.log(newVal, oldVal, 'num')
})
//watch监听reactive对象
const num2 = reactive({ num: 0 })
watch(
  () => num2.num,
  (newVal, oldVal) => {
    console.log(newVal, oldVal, 'num2')
  },
)
//watch监听多个值
watch([num, num2], ([newVal1, newVal2], [oldVal1, oldVal2]) => {
  console.log(newVal1, newVal2, oldVal1, oldVal2, 'all')
})

const stop = watchEffect(() => {
  //一开始就会执行一次 类似 watch immediate
  console.log('watchEffect', num.value)
  console.log('watchEffect', num2.num)
})

const testCompSet = ref('')
const otherTestCompSet = ref('')

const changetestCompSet = computed({
  get() {
    console.log('触发get')
    return testCompSet.value
  },
  set(val) {
    console.log('触发set', val)
    otherTestCompSet.value = val
  },
})
stop() //停止监听副作用
</script>

<template>
<div>
  <h1 :style="{ fontSize: '50px' }">Comp&Watch</h1>
  <label for="familyName">familyName: <input v-model="userInfo.familyName" type="text" /></label>
  <label for="lastName">lastName: <input v-model="userInfo.lastName" type="text" /></label>
  <p>userName:{{ userName }}</p>
  <p>userName2:{{ userName2 }}</p>
  <h2>num:{{ num }}</h2>
  <h2>num2:{{ num2.num }}</h2>
  <button @click="(num2.num++, num++)">num2++</button>
  <span>v-model 结合v-model</span>
  <input type="text" v-model="testCompSet" />
  <span>触发computed，set{{ changetestCompSet }}</span
  ><span>{{ otherTestCompSet }}</span>
</div>
</template>

<style scoped lang="scss"></style>
